package com.longdaji.decoration.ui.payOrder;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.longdaji.decoration.R;
import com.longdaji.decoration.base.BaseActivity;
import com.longdaji.decoration.data.bean.AddressBean;
import com.longdaji.decoration.data.bean.PayResult;
import com.longdaji.decoration.ui.payFinish.PayFinishActivity;
import com.longdaji.decoration.utils.ImageUtil;
import com.longdaji.decoration.utils.StringUtil;

import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by longtao on 2017/12/19.
 */

public class PayOrderActivity extends BaseActivity implements PayOrderContract.View{

    private static final String TAG = PayOrderActivity.class.getSimpleName();

    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_default_address)
    TextView mTvDefaultAddr;
    @BindView(R.id.tv_receiver)
    TextView mTvReceiverInfo;
    @BindView(R.id.tv_goods_price)
    TextView mTvGoodsPrice;
    @BindView(R.id.tv_freight_charge)
    TextView mTvFreightCharge;
    @BindView(R.id.tv_actual_pay)
    TextView mTvActualPay;
    @BindView(R.id.tv_need_pay)
    TextView mTvNeedPay;
    @BindView(R.id.tv_goods_num)
    TextView mTvGoodsNum;
    @BindView(R.id.iv_sku_image)
    ImageView mIvSkuImage;
    @BindView(R.id.tv_pakage_charge)
    TextView mTvPakageCharge;
    @BindView(R.id.tv_left_money_deduction)
    TextView mTvLeftMoneyDeduction;
    @BindView(R.id.tv_score_deduction)
    TextView mTvScoreDeduction;
    @Inject
    PayOrderPresenter mPresenter;
    private static final int SDK_PAY_FLAG = 1;
    private int num;
    private AddressBean.Address mDefaultAddress;
    private double mGoodmoney;
    private String mOrderId;
    private double mTotalMoney;

    public static Intent getStartIntent(Context context) {
        Intent intent = new Intent(context, PayOrderActivity.class);
        return intent;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(PayOrderActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent intent= PayFinishActivity.getStartIntent(PayOrderActivity.this);
                        intent.putExtra("money",mTotalMoney);
                        startActivity(intent);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PayOrderActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "PayOrderActivity onCreate");
        setContentView(R.layout.activity_pay_order);
        setUnBinder(ButterKnife.bind(this));
        initView();
    }

    private void initView() {
        mPresenter.setView(this);
        mTvTitle.setText("结算中心");
        if (getIntent() != null) {
            num = getIntent().getIntExtra("num", 0);
            mGoodmoney = getIntent().getDoubleExtra("good_money", 0);
            double pakageMoney = getIntent().getDoubleExtra("pakage_money", 0);
            double logisticsMoney = getIntent().getDoubleExtra("logistics_money", 0);
            double leftMoney = getIntent().getDoubleExtra("left_money", 0);
            double scoreMoney = getIntent().getDoubleExtra("score_money", 0);
             mTotalMoney = getIntent().getDoubleExtra("total_money", 0);
            mDefaultAddress = getIntent().getParcelableExtra("addr");
            String image = getIntent().getStringExtra("image");
             mOrderId = getIntent().getStringExtra("orderId");
            mTvGoodsNum.setText(num + "件商品");
            mTvGoodsPrice.setText("¥" + StringUtil.formatNumber(mGoodmoney));
            mTvPakageCharge.setText("¥" +  StringUtil.formatNumber(pakageMoney));
            mTvFreightCharge.setText("¥" +  StringUtil.formatNumber(logisticsMoney));
            mTvLeftMoneyDeduction.setText("-¥" +  StringUtil.formatNumber(leftMoney));
            mTvScoreDeduction.setText("-¥" +  StringUtil.formatNumber(scoreMoney));
            mTvNeedPay.setText("¥" +  StringUtil.formatNumber(mTotalMoney));
            mTvActualPay.setText("¥" +  StringUtil.formatNumber(mTotalMoney));
            if(mDefaultAddress!=null){
                mTvReceiverInfo.setText(mDefaultAddress.getContactPerson()+"  "+mDefaultAddress.getContactTelephone());
                mTvDefaultAddr.setText(mDefaultAddress.getSimpleAddress()+mDefaultAddress.getDetailAddress());
            }
//            Glide.with(this)
//                    .load(image)
//                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
//                    .placeholder(R.drawable.no_banner)
//                    .error(R.drawable.no_banner)
//                    .into(mIvSkuImage);
            ImageUtil.loadImage(this,image,mIvSkuImage);
        }
    }

    @Override
    protected void onDestroy() {
        mPresenter.detachView();
        super.onDestroy();
    }


    @OnClick({R.id.iv_back, R.id.btn_submit_order})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_submit_order:
                mPresenter.getPayOrderInfo(mOrderId,mTotalMoney);
                break;

            default:
                break;
        }
    }

    @Override
    public void showGetOrderInfoSuccess(String orderInfo) {
        aliPay(orderInfo);
    }

    @Override
    public void showGetOrderInfoFail() {
        toast("支付失败！");
    }

    /**
     * 支付宝支付业务
     */
    public void aliPay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayOrderActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.d("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

}
